<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Area as AreaModel;
use App\Models\CitySettings as CitySettingsModel;
use App\Models\SystemSettings as SystemSettingsModel;
use App\Utils\Tool;
use DB;

class SystemSettingsService
{
    public static $colsMap = [
        'sysName'      => 'sys_name',
        'sysLogo'      => 'sys_logo',
        'sysSlogan'    => 'sys_slogan',
        'sysIntro'     => 'sys_intro',
        'wxshareTitle' => 'wxshare_title',
        'wxshareDesc'  => 'wxshare_desc',
        'wxshareImage' => 'wxshare_image',
    ];

    // 不要删除
    public function __construct()
    {
        $this->systemSettingsM = new SystemSettingsModel();
        $this->citySettingsM   = new citySettingsModel();
    }

    /*
    *  获取系统配置信息
    */
    public function getSysSettings()
    {
        $data     = $main     = $defaults     = [];
        $settings = $this->systemSettingsM->get()->all();
        if ($settings) {
            foreach ((array) $settings as $setting) {
                $main[$setting->config_name] = $setting->config_value;
            }
        }
        $defaults = $this->citySettingsM->getDefaultSettings();
        if ($defaults) {
            $defaults['service_weekdays'] = Tool::weekdaysBin2Dec($defaults['service_weekdays']);
        }
        $areas                   = LocationService::getAntCityDataWithDash(0, true, false, false);
        $areas                   = CitySettingsService::antCityOwnSettings($areas);
        $openAreas               = AreaModel::getAllOpenDistrictAreasIdsWithDashes();
        $defaults['busyPeriods'] = CitySettingsService::getBusyPeriods(0);

        return [$main, $defaults, $areas, $openAreas];
        //$data = compact('main', 'defaults', 'areas');
        //return $data;
    }

    //保存主要配置信息
    public function saveSysSettings(array $main, string $areas, array $defaults)
    {
        DB::beginTransaction();
        //main
        if ($main) {
            foreach (self::$colsMap as $configName => $columnName) {
                if (!isset($main[$configName])) {
                    continue;
                }
                if ($this->systemSettingsM->sysSettingExists($columnName)) {
                    $upd = $this->systemSettingsM->updSettings($columnName, $main[$configName]);
                    if (!$upd) {
                        DB::rollback();

                        return false;
                    }
                } else {
                    $add = $this->systemSettingsM->addSettings($columnName, $main[$configName]);
                    if (!$add) {
                        DB::rollback();

                        return false;
                    }
                }
            }
        }
        //areas
        if ($areas) {
            $save = $this->systemSettingsM->updOpenCities($areas);
            if (!$save) {
                DB::rollback();

                return false;
            }
        }
        if ($defaults['busyPeriods'] ?? false) {
            $busyPeriods = $defaults['busyPeriods'];
            unset($defaults['busyPeriods']);
            CitySettingsService::clearCityBusyPeriods(0);
            CitySettingsService::addBatchCityBusyPeriods(0, $busyPeriods);
        }
        //defaults
        $updData           = [];
        $sysDefaultColsMap = CitySettingsService::$sysDefaultColsMap;
        foreach ($sysDefaultColsMap as $cityConfigName => $cityColName) {
            if (!isset($defaults[$cityConfigName])) {
                continue;
            }
            $defaultValue = $defaults[$cityConfigName];
            if (in_array($cityConfigName, ['serviceHourStart', 'serviceHourEnd'])) {//小时字符串转浮点数
                $defaultValue = $this->citySettingsM->hour2float($defaultValue);
            }
            if ($cityConfigName == 'serviceWeekdays' && $defaultValue) {//星期转为数组
                $weekDayArr = (array) array_map(function ($item) {
                    return intval(trim($item));
                }, (array) explode(',', (string) $defaultValue));
                $weekDayArr   = array_filter($weekDayArr);
                $defaultValue = Tool::weekdaysDec2Bin($weekDayArr);
            }
            if (in_array($cityConfigName, ['serviceInterval', 'reservationHour'])) {//判断0.5倍数
                if ((($defaultValue * 10) % 5) != 0 || $defaultValue > 24 * 7) {
                    continue;
                }
            }
            $updData[$cityColName] = $defaultValue;
        }
        if ($updData) {
            $save = $this->citySettingsM->updDefaultSettings($updData);
            if (!$save) {
                DB::rollback();

                return false;
            }
        }
        DB::commit();

        return true;
    }

    public function toggleCity(int $cityId, int $act)
    {
        $areaIds = AreaModel::getCityChildAreaIds($cityId);
        if ($areaIds) {
            $isOpen = $act ? 1 : 0;

            return AreaModel::toggleAreas($areaIds, $isOpen);
        }

        return false;
    }

    public function saveH5Settings(array $settings)
    {
        DB::beginTransaction();
        $save1 = self::saveSysSettings($settings, '', []);
        $save2 = true;
        $arr   = [];
        if (isset($settings['phoneNumber'])) {
            $arr['phoneNumber'] = $settings['phoneNumber'];
        }
        if (isset($settings['showPhone'])) {
            $arr['showPhone'] = $settings['showPhone'];
        }
        if ($arr) {
            $save2 = (new CitySettingsService())->saveCitySettings($arr, 0);
        }
        if ($save1 && $save2) {
            DB::commit();

            return true;
        }
        DB::rollback();

        return false;
    }
}
